package liuyuyang.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import liuyuyang.domain.User;
import liuyuyang.pojo.Result;
import liuyuyang.service.UserService;
import liuyuyang.utils.Jwt;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserService userService;
    @Resource
    private Jwt jwt;

    // 登录
    @PostMapping("/login")
    public Result login(@RequestBody User user) {
        try {
            User login = userService.login(user.getUsername(), user.getPassword());

            // 生成Token
            String token = jwt.createToken(user);

            Map<String, Object> data = new HashMap<>();
            data.put("token", token);
            data.put("user", userService.get(login.getUid()));

            return Result.success("登录成功", data);
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return Result.error("登录失败：" + e.getMessage());
        }
    }

    // 校验
    @PostMapping("/verify")
    public Result verify(@RequestBody User user) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_name", user.getUsername());

        User data = userService.getOne(queryWrapper);

        if (data != null) {
            return Result.success("校验成功");
        } else {
            return Result.error("用户可能不存在");
        }
    }

    // 重置密码
    @PostMapping("/reset/{uid}")
    public Result<String> reset(@PathVariable Integer uid) {
        try {
            userService.reset(uid);

            return Result.success("重置密码成功");
        } catch (Exception e) {
            return Result.error("重置密码失败" + e.getMessage());
        }
    }

    @PatchMapping
    public Result<String> edit(@RequestBody User user) {
        try {
            userService.edit(user);

            return Result.success("编辑成功");
        } catch (Exception e) {
            return Result.error("编辑失败：" + e.getMessage());
        }
    }

    // 修改密码
    @PatchMapping("/pass")
    public Result<String> editPass(@RequestBody User user) {
        System.out.println(user);

        try {
            userService.editPass(user);

            return Result.success("修改密码成功");
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    // 获取用户信息
    @GetMapping("/{uid}")
    public Result<User> get(@PathVariable Integer uid) {
        return Result.success(userService.get(uid));
    }

    @GetMapping
    public Result<List<User>> list() {
        return Result.success(userService.list());
    }
}
